package com.sany.canwifi.udp;

import android.util.Log;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * author : dingqb
 * e-mail : dingqb@sany.com.cn
 * date   : 2022/1/4 6:52 PM
 * desc   :
 * version: 1.0
 */
public class MulticastListener {
    public static final String TAG = "MulticastListener";
    private int port;
    private String host;

    public MulticastListener(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void listen() {
        byte[] data = new byte[256];
        try {
            InetAddress ip = InetAddress.getByName(this.host);
            Log.e(TAG, "listen: host=="+host );
            MulticastSocket ms = new MulticastSocket(this.port);
            ms.joinGroup(ip);
            DatagramPacket packet = new DatagramPacket(data, data.length);
            //receive()是阻塞方法，会等待客户端发送过来的信息
            ms.receive(packet);
            String message = new String(packet.getData(), 0, packet.getLength());
            System.out.println(message);
            Log.e(TAG, "listen: message=" + message);
            ms.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


